<?php
/**
 * Custom comments functions for Wanzicms theme.
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

// 获取默认头像URL
$default_avatar = get_template_directory_uri() . '/assets/images/default-avatar.png';
// 如果默认头像文件不存在，使用一个在线的默认头像
if (!file_exists(get_template_directory() . '/assets/images/default-avatar.png')) {
    $default_avatar = '';
}

// 获取当前用户头像
function get_user_avatar_url($user_id = 0, $size = 96) {
    if ($user_id === 0 && !is_user_logged_in()) {
        // 用户未登录，返回默认头像
        global $default_avatar;
        return $default_avatar;
    }
    
    if ($user_id === 0) {
        $user_id = get_current_user_id();
    }
    
    $avatar_url = get_avatar_url($user_id, array('size' => $size));
    
    // 如果获取不到头像，使用默认头像
    if (empty($avatar_url) || $avatar_url === false) {
        global $default_avatar;
        return $default_avatar;
    }
    
    // 如果是Gravatar且访问困难，替换为国内镜像
    if (strpos($avatar_url, 'gravatar.com') !== false) {
        $avatar_url = str_replace('//www.gravatar.com/avatar', '//cn.gravatar.com/avatar', $avatar_url);
        // 或者使用V2EX提供的Gravatar镜像
        // $avatar_url = str_replace('//www.gravatar.com/avatar', '//cdn.v2ex.com/gravatar', $avatar_url);
    }
    
    return $avatar_url;
}

// 获取评论者头像
function get_comment_avatar($comment, $size = 96, $class = '') {
    if (empty($comment->comment_author_email)) {
        global $default_avatar;
        $avatar_url = $default_avatar;
    } else {
        $avatar_url = get_avatar_url($comment->comment_author_email, array('size' => $size));
        
        // 如果获取不到头像，使用默认头像
        if (empty($avatar_url) || $avatar_url === false) {
            global $default_avatar;
            $avatar_url = $default_avatar;
        }
        
        // 如果是Gravatar且访问困难，替换为国内镜像
        if (strpos($avatar_url, 'gravatar.com') !== false) {
            $avatar_url = str_replace('//www.gravatar.com/avatar', '//cn.gravatar.com/avatar', $avatar_url);
            // 或者使用V2EX提供的Gravatar镜像
            // $avatar_url = str_replace('//www.gravatar.com/avatar', '//cdn.v2ex.com/gravatar', $avatar_url);
        }
    }
    
    return '<img src="' . esc_url($avatar_url) . '" alt="用户头像" class="' . esc_attr($class) . '" loading="lazy">';
}

// 添加评论图片上传功能
function wanzicms_enqueue_comment_scripts()
{
    if (is_singular() && comments_open()) {
        // 确保jQuery加载
        wp_enqueue_script('jquery');

        // 确保comment-reply脚本加载
        wp_enqueue_script('comment-reply');

        // 不再在这里添加wp_localize_script，避免与wanzicms_comment_scripts冲突
    }
}
add_action('wp_enqueue_scripts', 'wanzicms_enqueue_comment_scripts');

// 处理评论图片上传
function wanzicms_upload_comment_image()
{
    // 验证nonce
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'comment_upload_nonce')) {
        wp_send_json_error(array('message' => '安全验证失败'));
    }

    // 检查用户权限
    if (!is_user_logged_in() && !get_option('comment_registration')) {
        // 允许未登录用户上传
    } elseif (!is_user_logged_in()) {
        wp_send_json_error(array('message' => '请先登录后再上传图片'));
    }

    // 检查是否有文件上传
    if (empty($_FILES['image'])) {
        wp_send_json_error(array('message' => '没有选择文件'));
    }

    // 获取WordPress上传目录信息
    $upload_dir = wp_upload_dir();

    // 创建评论图片目录
    $comment_upload_dir = $upload_dir['basedir'] . '/comment-images';
    if (!file_exists($comment_upload_dir)) {
        wp_mkdir_p($comment_upload_dir);
    }

    // 处理文件
    $file = $_FILES['image'];

    // 检查文件类型
    $allowed_types = array('image/jpeg', 'image/png', 'image/gif', 'image/webp');
    if (!in_array($file['type'], $allowed_types)) {
        wp_send_json_error(array('message' => '只允许上传JPG、PNG、GIF或WEBP格式的图片'));
    }

    // 检查文件大小（限制为2MB）
    if ($file['size'] > 2 * 1024 * 1024) {
        wp_send_json_error(array('message' => '图片大小不能超过2MB'));
    }

    // 生成唯一文件名
    $filename = uniqid() . '-' . sanitize_file_name($file['name']);
    $file_path = $comment_upload_dir . '/' . $filename;

    // 移动上传的文件
    if (move_uploaded_file($file['tmp_name'], $file_path)) {
        // 生成URL
        $file_url = $upload_dir['baseurl'] . '/comment-images/' . $filename;

        // 返回成功响应
        wp_send_json_success(array(
            'url' => $file_url,
            'filename' => $filename
        ));
    } else {
        wp_send_json_error(array('message' => '上传失败，请重试'));
    }
}
add_action('wp_ajax_upload_comment_image', 'wanzicms_upload_comment_image');
add_action('wp_ajax_nopriv_upload_comment_image', 'wanzicms_upload_comment_image');

// 支持评论中的Markdown图片
function wanzicms_comment_text_filter($content)
{
    // 简单的Markdown图片转换为HTML
    $pattern = '/!\[(.*?)\]\((.*?)\)/';
    $replacement = '<img src="$2" alt="$1" class="comment-image">';
    $content = preg_replace($pattern, $replacement, $content);

    return $content;
}
add_filter('comment_text', 'wanzicms_comment_text_filter');

// 添加评论点赞功能
function wanzicms_comment_likes_setup()
{
    // 注册评论点赞AJAX处理函数
    add_action('wp_ajax_like_comment', 'wanzicms_like_comment');
    add_action('wp_ajax_unlike_comment', 'wanzicms_unlike_comment');
    add_action('wp_ajax_nopriv_like_comment', 'wanzicms_like_comment_guest');
    add_action('wp_ajax_nopriv_unlike_comment', 'wanzicms_unlike_comment_guest');

    // 将点赞数据传递给前端
    add_action('wp_enqueue_scripts', 'wanzicms_comment_scripts');
}
add_action('init', 'wanzicms_comment_likes_setup');

// 注册评论相关脚本
function wanzicms_comment_scripts()
{
    // 只在文章页面和页面加载评论脚本
    if (is_singular() && comments_open()) {
        // 注册评论脚本
        wp_localize_script('jquery', 'wp_comment_params', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'like_nonce' => wp_create_nonce('comment_like_nonce'),
            'reply_nonce' => wp_create_nonce('comment_reply_nonce'),
            'upload_nonce' => wp_create_nonce('comment_upload_nonce'),
            'is_user_logged_in' => is_user_logged_in()
        ));
    }
}

// 处理已登录用户的评论点赞
function wanzicms_like_comment()
{
    // 验证nonce
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'comment_like_nonce')) {
        wp_send_json_error(array('message' => '安全验证失败'));
    }

    // 获取评论ID
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    if (!$comment_id) {
        wp_send_json_error(array('message' => '无效的评论ID'));
    }

    // 获取当前用户ID
    $user_id = get_current_user_id();

    // 获取已点赞的用户列表
    $liked_users = get_comment_meta($comment_id, 'liked_users', true);
    if (!is_array($liked_users)) {
        $liked_users = array();
    }

    // 检查用户是否已经点赞
    if (in_array($user_id, $liked_users)) {
        wp_send_json_error(array('message' => '您已经点赞过了'));
    }

    // 添加用户到点赞列表
    $liked_users[] = $user_id;
    update_comment_meta($comment_id, 'liked_users', $liked_users);

    // 更新点赞总数
    $likes_count = count($liked_users);
    update_comment_meta($comment_id, 'comment_likes', $likes_count);

    wp_send_json_success(array('likes' => $likes_count));
}

// 处理已登录用户的取消点赞
function wanzicms_unlike_comment()
{
    // 验证nonce
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'comment_like_nonce')) {
        wp_send_json_error(array('message' => '安全验证失败'));
    }

    // 获取评论ID
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    if (!$comment_id) {
        wp_send_json_error(array('message' => '无效的评论ID'));
    }

    // 获取当前用户ID
    $user_id = get_current_user_id();

    // 获取已点赞的用户列表
    $liked_users = get_comment_meta($comment_id, 'liked_users', true);
    if (!is_array($liked_users)) {
        $liked_users = array();
    }

    // 检查用户是否已经点赞
    if (!in_array($user_id, $liked_users)) {
        wp_send_json_error(array('message' => '您尚未点赞'));
    }

    // 从点赞列表中移除用户
    $liked_users = array_diff($liked_users, array($user_id));
    update_comment_meta($comment_id, 'liked_users', $liked_users);

    // 更新点赞总数
    $likes_count = count($liked_users);
    update_comment_meta($comment_id, 'comment_likes', $likes_count);

    wp_send_json_success(array('likes' => $likes_count));
}

// 处理游客的评论点赞 (使用Cookie记录)
function wanzicms_like_comment_guest()
{
    // 验证nonce
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'comment_like_nonce')) {
        wp_send_json_error(array('message' => '安全验证失败'));
    }

    // 获取评论ID
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    if (!$comment_id) {
        wp_send_json_error(array('message' => '无效的评论ID'));
    }

    // 生成唯一的游客标识
    $guest_id = isset($_COOKIE['comment_guest_id']) ? $_COOKIE['comment_guest_id'] : uniqid('guest_');
    setcookie('comment_guest_id', $guest_id, time() + 30 * DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN);

    // 获取已点赞的游客列表
    $liked_guests = get_comment_meta($comment_id, 'liked_guests', true);
    if (!is_array($liked_guests)) {
        $liked_guests = array();
    }

    // 检查游客是否已经点赞
    if (in_array($guest_id, $liked_guests)) {
        wp_send_json_error(array('message' => '您已经点赞过了'));
    }

    // 添加游客到点赞列表
    $liked_guests[] = $guest_id;
    update_comment_meta($comment_id, 'liked_guests', $liked_guests);

    // 获取已点赞的用户列表
    $liked_users = get_comment_meta($comment_id, 'liked_users', true);
    if (!is_array($liked_users)) {
        $liked_users = array();
    }

    // 更新点赞总数
    $likes_count = count($liked_users) + count($liked_guests);
    update_comment_meta($comment_id, 'comment_likes', $likes_count);

    wp_send_json_success(array('likes' => $likes_count));
}

// 处理游客的取消点赞
function wanzicms_unlike_comment_guest()
{
    // 验证nonce
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'comment_like_nonce')) {
        wp_send_json_error(array('message' => '安全验证失败'));
    }

    // 获取评论ID
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    if (!$comment_id) {
        wp_send_json_error(array('message' => '无效的评论ID'));
    }

    // 获取游客标识
    $guest_id = isset($_COOKIE['comment_guest_id']) ? $_COOKIE['comment_guest_id'] : '';
    if (!$guest_id) {
        wp_send_json_error(array('message' => '无法识别游客身份'));
    }

    // 获取已点赞的游客列表
    $liked_guests = get_comment_meta($comment_id, 'liked_guests', true);
    if (!is_array($liked_guests)) {
        $liked_guests = array();
    }

    // 检查游客是否已经点赞
    if (!in_array($guest_id, $liked_guests)) {
        wp_send_json_error(array('message' => '您尚未点赞'));
    }

    // 从点赞列表中移除游客
    $liked_guests = array_diff($liked_guests, array($guest_id));
    update_comment_meta($comment_id, 'liked_guests', $liked_guests);

    // 获取已点赞的用户列表
    $liked_users = get_comment_meta($comment_id, 'liked_users', true);
    if (!is_array($liked_users)) {
        $liked_users = array();
    }

    // 更新点赞总数
    $likes_count = count($liked_users) + count($liked_guests);
    update_comment_meta($comment_id, 'comment_likes', $likes_count);

    wp_send_json_success(array('likes' => $likes_count));
}

// 添加评论回复AJAX处理函数
function wanzicms_submit_comment_reply()
{
    // 验证nonce
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'comment_reply_nonce')) {
        wp_send_json_error(array('message' => '安全验证失败'));
    }

    // 检查用户是否登录
    if (!is_user_logged_in()) {
        wp_send_json_error(array('message' => '请先登录后再回复'));
    }

    // 获取评论ID和内容
    $comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;
    $content = isset($_POST['content']) ? sanitize_textarea_field($_POST['content']) : '';

    if (!$comment_id) {
        wp_send_json_error(array('message' => '无效的评论ID'));
    }

    if (empty($content)) {
        wp_send_json_error(array('message' => '回复内容不能为空'));
    }

    // 获取原始评论信息
    $parent_comment = get_comment($comment_id);
    if (!$parent_comment) {
        wp_send_json_error(array('message' => '找不到原始评论'));
    }

    // 准备评论数据
    $current_user = wp_get_current_user();
    $comment_data = array(
        'comment_post_ID' => $parent_comment->comment_post_ID,
        'comment_author' => $current_user->display_name,
        'comment_author_email' => $current_user->user_email,
        'comment_author_url' => $current_user->user_url,
        'comment_content' => $content,
        'comment_parent' => $comment_id,
        'user_id' => $current_user->ID,
        'comment_approved' => 1, // 自动审核通过
    );

    // 插入评论
    $new_comment_id = wp_insert_comment($comment_data);

    if ($new_comment_id) {
        wp_send_json_success(array(
            'comment_id' => $new_comment_id,
            'no_moderation' => true
        ));
    } else {
        wp_send_json_error(array('message' => '回复提交失败，请重试'));
    }
}
add_action('wp_ajax_submit_comment_reply', 'wanzicms_submit_comment_reply');


// 在评论表单底部添加图片上传按钮
function add_image_upload_button_after_comment() {
    // 不再在此处添加按钮，而是通过JavaScript添加到评论框底部
}
add_action('comment_form_after_fields', 'add_image_upload_button_after_comment');
add_action('comment_form_logged_in_after', 'add_image_upload_button_after_comment');

// 添加提交按钮容器
function add_submit_button_container() {
    echo '<div class="submit-button-container"></div>';
}
add_action('comment_form_after', 'add_submit_button_container');

/**
 * 创建评论回复通知
 *
 * @param int   $comment_id The comment ID.
 * @param obj   $comment_object The comment object.
 */
function wanzicms_notify_on_comment_reply($comment_id, $comment_object) {
    // 检查这是否是一个回复
    if ($comment_object->comment_parent) {
        $parent_comment = get_comment($comment_object->comment_parent);
        $parent_author_id = $parent_comment->user_id;
        $reply_author_id = $comment_object->user_id;

        // 确保父评论的作者存在且不是匿名用户，并且回复者不是自己
        if ($parent_author_id != 0 && $parent_author_id != $reply_author_id) {
            
            // 获取所有通知
            $notifications = get_user_meta($parent_author_id, '_user_notifications', true);
            if (!is_array($notifications)) {
                $notifications = [];
            }

            // 创建新通知
            $new_notification = [
                'id'         => 'cmt-' . $comment_id, // 使用评论ID确保唯一性
                'type'       => 'comment_reply',
                'message'    => '<strong>' . esc_html($comment_object->comment_author) . '</strong> 回复了您的评论',
                'content'    => wp_trim_words(esc_html($comment_object->comment_content), 20, '...'),
                'link'       => get_comment_link($comment_id),
                'timestamp'  => time(),
                'is_read'    => false,
            ];

            // 将新通知添加到数组的开头
            array_unshift($notifications, $new_notification);

            // 更新用户元数据
            update_user_meta($parent_author_id, '_user_notifications', $notifications);
        }
    }
}
add_action('wp_insert_comment', 'wanzicms_notify_on_comment_reply', 10, 2);

/**
 * AJAX handler to mark all notifications as read.
 */
function wanzicms_mark_all_notifications_read() {
    // Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mark_notifications_read_nonce')) {
        wp_send_json_error(['message' => '安全验证失败。']);
        return;
    }

    if (!is_user_logged_in()) {
        wp_send_json_error(['message' => '请先登录。']);
        return;
    }

    $user_id = get_current_user_id();
    $notifications = get_user_meta($user_id, '_user_notifications', true);

    if (!empty($notifications) && is_array($notifications)) {
        foreach ($notifications as &$notification) {
            $notification['is_read'] = true;
        }
        update_user_meta($user_id, '_user_notifications', $notifications);
    }

    wp_send_json_success();
}
add_action('wp_ajax_mark_all_notifications_read', 'wanzicms_mark_all_notifications_read');
